import vue from '../main'
import store from '../store/index';
import { Loading } from 'element-ui';
import { checkStr  } from "./methods"
import { OBJ } from "./init"
import { PARAMS } from "./params"

/**
 * 显示WIFI设置
 * flag :true显示  :false不显示
 * 如果用户引导程序未结束，显示建图
 * **/
export function showWifi(flag){
    if(flag){
        store.commit('switchWifiSetting', true);
    }else{
        store.commit('switchWifiSetting', false);
    }
}

/**
 * wifi复位
 * **/
export function wifiRest(options) {
    options['mode'] = PARAMS.NetworkMode.ap;
    var optionStr = `~/catkin_ws/www/shell/comm.sh -m ap`;
    var msg = new ROSLIB.Message({
        data: optionStr
    });
    OBJ.topic.netWorkTopic.publish(msg);
    store.commit('switchWifiSetting', false);
    // reconnect
    Loading.service({
        text: vue.$t("inTheSwitch")
    })
    setTimeout(function () {
        window.location.href = `http://10.42.0.1`;
        Loading.service().close();
    }, 3000);
    store.commit('switchWifiSetting', false);
};


/**
 * 提交WiFi设置
 * 缓存当前引导步骤为wifi
 * 引导次数++
 * IP
 *   自动IP
 *      就不需要输入IP/MASK/GATEWAY
 *   手动IP
 *      需要判断安卓或苹果
 *      安卓：192.168.43.xxx     xx：0-255之间
 *      苹果：172.20.10.xx       xx：2-20之间
 * 保存设置 
 *   -a自动连接 /不会自动连接
 * 复位
 *   AP模式
 * **/
export function subWifiSet(options) {
    window.localStorage.setItem('guideName', 'wifi');

    let { ssid, password, ip, mask, gateway, checked, selectIP } = options;
    options['mode'] = PARAMS.NetworkMode.wifi;
    let optionStr = "~/catkin_ws/www/shell/comm.sh -m wifi ";
    if (!ssid || !password || !checkStr(ssid)) {
        Notification({
            title: vue.$t("titles.error"),
            message: vue.$t("messages.wifiNameOrPswUnavailable"),
            type: 'error',
            position: 'top-left',
            offset: 100
        });
        return;
    }
    optionStr += `-s ${ssid} -p ${password}`;
    /**
     * 如果是自动IP不需要传IP/MASK/GATEWAY
     * **/
    if(selectIP){
        //校验ip(必选)
        if (!checkIp(ip)) {
            Notification({
                title: vue.$t("titles.error"),
                message: vue.$t("messages.ipUnavailable"),
                type: 'error',
                position: 'top-left',
                offset: 100
            });
            return;
        }
        optionStr += ` -i ${ip}`;

        //子掩码(可选)，十进制转换为二进制，数字相加
        let num = 0;
        if (mask !== "") {
            let arrMask = mask.split(".");
            for (let i = 0; i < arrMask.length; i++) {
                let arrConvert = Number(arrMask[i]).toString(2).split("");
                for (let j = 0; j < arrConvert.length; j++) {
                    num = num + Number(arrConvert[j])
                }
            }
            optionStr += ` -k ${num}`;
        }
        //网关(可选)
        if(gateway !== ""){
            optionStr += ` -g ${gateway}`;
        }
        //-a：永久保存
        if(checked){
            optionStr += ` -a`
        }

    }else{
        //自动ip模式
        optionStr = checked ? `~/catkin_ws/www/shell/comm.sh -m wifi -s ${ssid} -p ${password} -a` : `~/catkin_ws/www/shell/comm.sh -m wifi -s ${ssid} -p ${password}`
    }

    var msg = new ROSLIB.Message({
        data: optionStr
    });

    console.log(`[INFO] ${JSON.stringify(msg)}`)
    OBJ.topic.netWorkTopic.publish(msg);
    var storage = window.localStorage;
    storage.setItem('wifiInfos', JSON.stringify(options));
    store.commit('switchWifiSetting', false);
    Loading.service({
        text: vue.$t("inTheSwitch")
    })

    setTimeout(function () {
        // window.location.href = `http://${ip}`;
        window.history.pushState({},0, `${ip}`);
        Loading.service().close();
        showWifi(false);
    }, 10000);
};

/**
 * 检索ip是否匹配
 * ipStr    ip地址
 * isMobile 机型
 * 如果为ios，最后一位在2-20之间
 * **/
function checkIp(ipStr) {
    //match字符串内检索指定的值
    ipStr = ipStr.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/g);
    if (ipStr == null) {
        return false;
    }
    //正则匹配的第几个子匹配字符串
    else if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255) {
        return false;
    }
    else {
        return true;
    }
}